import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../services/app_state_service.dart';
import '../widgets/loading_overlay.dart';

/// 页面基类
/// 提供所有页面的通用功能和状态管理
abstract class BasePage extends StatefulWidget {
  const BasePage({super.key});
}

/// 页面基类状态
/// 提供通用的页面状态管理和工具方法
abstract class BasePageState<T extends BasePage> extends State<T> {
  // 页面状态
  bool _isLoading = false;
  String? _errorMessage;
  
  // 获取应用状态服务
  AppStateService get appState => AppStateService();
  
  // 页面加载状态
  bool get isLoading => _isLoading;
  String? get errorMessage => _errorMessage;
  
  @override
  void initState() {
    super.initState();
    onPageInit();
  }
  
  @override
  void dispose() {
    onPageDispose();
    super.dispose();
  }
  
  /// 页面初始化
  /// 子类可以重写此方法进行页面特定的初始化
  void onPageInit() {}
  
  /// 页面销毁
  /// 子类可以重写此方法进行页面特定的清理
  void onPageDispose() {}
  
  /// 设置加载状态
  void setLoading(bool loading) {
    if (mounted) {
      setState(() {
        _isLoading = loading;
      });
    }
  }
  
  /// 设置错误信息
  void setError(String? error) {
    if (mounted) {
      setState(() {
        _errorMessage = error;
      });
    }
  }
  
  /// 清除错误信息
  void clearError() {
    if (mounted) {
      setState(() {
        _errorMessage = null;
      });
    }
  }
  
  /// 显示加载状态
  void showLoading([String? message]) {
    setLoading(true);
    if (message != null) {
      _showSnackBar(message);
    }
  }
  
  /// 隐藏加载状态
  void hideLoading() {
    setLoading(false);
  }
  
  /// 显示成功消息
  void showSuccess(String message) {
    _showSnackBar(message, backgroundColor: Colors.green);
  }
  
  /// 显示错误消息
  void showError(String message) {
    _showSnackBar(message, backgroundColor: Colors.red);
  }
  
  /// 显示警告消息
  void showWarning(String message) {
    _showSnackBar(message, backgroundColor: Colors.orange);
  }
  
  /// 显示信息消息
  void showInfo(String message) {
    _showSnackBar(message);
  }
  
  /// 显示确认对话框
  Future<bool?> showConfirmDialog({
    required String title,
    required String content,
    String confirmText = '确定',
    String cancelText = '取消',
    bool isDestructive = false,
  }) {
    return showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(title),
        content: Text(content),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: Text(cancelText),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(true),
            style: isDestructive
                ? TextButton.styleFrom(foregroundColor: Colors.red)
                : null,
            child: Text(confirmText),
          ),
        ],
      ),
    );
  }
  
  /// 显示输入对话框
  Future<String?> showInputDialog({
    required String title,
    required String hintText,
    String? initialValue,
    String confirmText = '确定',
    String cancelText = '取消',
    TextInputType? keyboardType,
  }) {
    final controller = TextEditingController(text: initialValue);
    
    return showDialog<String>(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(title),
        content: TextField(
          controller: controller,
          decoration: InputDecoration(hintText: hintText),
          keyboardType: keyboardType,
          autofocus: true,
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text(cancelText),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(controller.text),
            child: Text(confirmText),
          ),
        ],
      ),
    );
  }
  
  /// 显示底部选择器
  Future<R?> showBottomSheet<R>({
    required Widget child,
    bool isScrollControlled = true,
    bool isDismissible = true,
    bool enableDrag = true,
  }) {
    return showModalBottomSheet<R>(
      context: context,
      isScrollControlled: isScrollControlled,
      isDismissible: isDismissible,
      enableDrag: enableDrag,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16.r)),
      ),
      builder: (context) => child,
    );
  }
  
  /// 显示全屏对话框
  Future<R?> showFullScreenDialog<R>(Widget child) {
    return Navigator.of(context).push<R>(
      MaterialPageRoute(
        builder: (context) => child,
        fullscreenDialog: true,
      ),
    );
  }
  
  /// 返回上一页
  void goBack([dynamic result]) {
    Navigator.of(context).pop(result);
  }
  
  /// 跳转到指定页面
  Future<R?> navigateTo<R>(Widget page) {
    return Navigator.of(context).push<R>(
      MaterialPageRoute(builder: (context) => page),
    );
  }
  
  /// 替换当前页面
  void replaceWith(Widget page) {
    Navigator.of(context).pushReplacement(
      MaterialPageRoute(builder: (context) => page),
    );
  }
  
  /// 清除所有页面并跳转
  void navigateAndClear(Widget page) {
    Navigator.of(context).pushAndRemoveUntil(
      MaterialPageRoute(builder: (context) => page),
      (route) => false,
    );
  }
  
  /// 显示SnackBar
  void _showSnackBar(String message, {Color? backgroundColor}) {
    if (!mounted) return;
    
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: backgroundColor,
        duration: const Duration(seconds: 2),
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8.r),
        ),
      ),
    );
  }
  
  /// 构建页面内容
  /// 子类必须实现此方法
  Widget buildPageContent(BuildContext context);
  
  /// 构建应用栏
  /// 子类可以重写此方法自定义应用栏
  PreferredSizeWidget? buildAppBar(BuildContext context) {
    return null;
  }
  
  /// 构建浮动操作按钮
  /// 子类可以重写此方法自定义浮动操作按钮
  Widget? buildFloatingActionButton(BuildContext context) {
    return null;
  }
  
  /// 构建底部导航栏
  /// 子类可以重写此方法自定义底部导航栏
  Widget? buildBottomNavigationBar(BuildContext context) {
    return null;
  }
  
  /// 构建抽屉
  /// 子类可以重写此方法自定义抽屉
  Widget? buildDrawer(BuildContext context) {
    return null;
  }
  
  /// 构建结束抽屉
  /// 子类可以重写此方法自定义结束抽屉
  Widget? buildEndDrawer(BuildContext context) {
    return null;
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: buildAppBar(context),
      body: LoadingOverlay(
        isLoading: _isLoading,
        child: buildPageContent(context),
      ),
      floatingActionButton: buildFloatingActionButton(context),
      bottomNavigationBar: buildBottomNavigationBar(context),
      drawer: buildDrawer(context),
      endDrawer: buildEndDrawer(context),
    );
  }
}

/// 无状态页面基类
/// 提供无状态页面的通用功能
abstract class BaseStatelessPage extends StatelessWidget {
  const BaseStatelessPage({super.key});
  
  /// 获取应用状态服务
  AppStateService get appState => AppStateService();
  
  /// 显示SnackBar
  void showSnackBar(BuildContext context, String message, {Color? backgroundColor}) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: backgroundColor,
        duration: const Duration(seconds: 2),
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8.r),
        ),
      ),
    );
  }
  
  /// 显示成功消息
  void showSuccess(BuildContext context, String message) {
    showSnackBar(context, message, backgroundColor: Colors.green);
  }
  
  /// 显示错误消息
  void showError(BuildContext context, String message) {
    showSnackBar(context, message, backgroundColor: Colors.red);
  }
  
  /// 显示警告消息
  void showWarning(BuildContext context, String message) {
    showSnackBar(context, message, backgroundColor: Colors.orange);
  }
  
  /// 显示信息消息
  void showInfo(BuildContext context, String message) {
    showSnackBar(context, message);
  }
  
  /// 跳转到指定页面
  Future<R?> navigateTo<R>(BuildContext context, Widget page) {
    return Navigator.of(context).push<R>(
      MaterialPageRoute(builder: (context) => page),
    );
  }
  
  /// 替换当前页面
  void replaceWith(BuildContext context, Widget page) {
    Navigator.of(context).pushReplacement(
      MaterialPageRoute(builder: (context) => page),
    );
  }
  
  /// 清除所有页面并跳转
  void navigateAndClear(BuildContext context, Widget page) {
    Navigator.of(context).pushAndRemoveUntil(
      MaterialPageRoute(builder: (context) => page),
      (route) => false,
    );
  }
}
